package com.xzy.seckill.controller;


import com.xzy.seckill.common.result.R;
import com.xzy.seckill.common.result.ResponseEnum;
import com.xzy.seckill.pojo.dto.LoginDTO;
import com.xzy.seckill.pojo.dto.RegisterDTO;
import com.xzy.seckill.pojo.vo.LoginVO;

import com.xzy.seckill.service.UserService;
import com.xzy.seckill.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xzy
 * @since 2022-01-24
 */
@RestController
@RequestMapping("/admin/tUser")
@Api(tags = "用户操作相关接口")
public class UserController {

    @Autowired
    UserService userService;

    //@Valid注解表示spring将会对入参进行校验，校验规则为此pojo上定义的注解 之后的业务逻辑中便不需要参数校验了
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public R doLogin(@Valid LoginDTO loginDTO){

        LoginVO login = userService.login(loginDTO);

        return R.ok().data("user",login).message("登录成功");
    }

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public R register(@ApiParam(value = "注册对象", required = true)
                      @RequestBody RegisterDTO registerDTO) {



        userService.register(registerDTO);

        return R.ok().message("注册成功");
    }

    @ApiOperation("校验令牌")
    @GetMapping("/checkToken")
    public R checkToken(HttpServletRequest request) {

        String token = request.getHeader("token");  // 获取令牌(前端将token放入请求头中)


        boolean result = JwtUtils.checkToken(token);
        System.out.println(token);
        System.out.println(result);

        if (result) {
            return R.ok();
        } else {
            return R.setResult(ResponseEnum.LOGIN_AUTH_ERROR);
        }
    }

}

